package dmsxl.lianbiao;

/**
 * Author: Zhang Dongwei
 * Date: 2023/4/7 19:50
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 */
public class lb5_19 {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

//        ListNode node1 = new ListNode(1);
//        ListNode node2 = new ListNode(2);
//        ListNode node3 = new ListNode(3);
//        node1.next = node2;
//        node2.next = node3;

        int n = 2;
        ListNode res = removeNthFromEnd(node1, n);
        while (res != null){
            System.out.println(res.val);
            res = res.next;
        }
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummynode = new ListNode(-1);
        dummynode.next = head;
        ListNode fast = dummynode;
        ListNode slow = dummynode;
        for (int i=0; i<n; i++){
            fast = fast.next;
        }
        while (fast.next != null){
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return dummynode.next;
    }
}
